package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.EmailReverseCheckService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 邮件反查控制器
 * 提供通过邮箱地址查询相关企业或用户信息的API
 */
@RestController
@RequestMapping("/email-reverse-check")
public class EmailReverseCheckController {

    private static final Logger log = LoggerFactory.getLogger(EmailReverseCheckController.class);
    
    // 创建线程池用于并发搜索
    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Autowired
    private EmailReverseCheckService emailReverseCheckService;
    
    @Autowired
    private WorkbenchStatsService workbenchStatsService;
    
    @Autowired
    private UserBalanceService userBalanceService;

    /**
     * 邮件反查API
     * 通过邮箱地址查询相关企业或用户信息
     * 
     * @param email 邮箱地址
     * @param page 页码
     * @param size 每页数量
     * @return 查询结果
     */
    @GetMapping("")
    public Map<String, Object> lookupByEmail(
            @RequestParam String email,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 添加详细调试日志
        log.info("收到邮件反查请求: 邮箱={}, 页码={}, 页大小={}", email, page, size);
        
        // 获取当前用户ID
        Long userId = UserContext.getUserId();
            
        // 邮件反查属于特殊操作，无论是第几页都需要扣除额度
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getReverseLookupRemaining() < size) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("success", false);
                errorResult.put("message", "您的反查次数余额不足，请充值后再查看");
                return errorResult;
            }
            
            // 调用服务进行查询
            Map<String, Object> result = emailReverseCheckService.lookupByEmail(email, page, size);
            log.info("查询结果总数: {}", result.containsKey("total") ? result.get("total") : "未知");
            
            // 获取实际返回的数据条数
            int actualCount = 0;
            if (result.containsKey("results") && result.get("results") instanceof List) {
                actualCount = ((List<?>) result.get("results")).size();
            }
            
            // 扣除用户反查余额
            if (actualCount > 0) {
                userBalanceService.deductReverseLookup(userId, actualCount);
            }
            
            // 增加邮件反查次数统计
            workbenchStatsService.incrementEmailReverseCount(userId);
            
            return result;
    }

    /**
     * 批量邮件反查接口
     * 读取Excel文件并进行批量反查，返回Excel结果文件
     */
    @PostMapping("/batch")
    public ResponseEntity<?> batchReverseLookup(@RequestParam("file") MultipartFile file) {
        log.info("收到批量邮件反查请求");

        // 获取当前用户ID
        Long userId = UserContext.getUserId();

        try {
            // 检查文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Result.error("请选择要上传的Excel文件"));
            }

            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return ResponseEntity.badRequest().body(Result.error("文件格式不正确，只支持.xlsx和.xls格式"));
            }

            // 读取Excel文件
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int totalRows = sheet.getPhysicalNumberOfRows();

            if (totalRows <= 1) {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("上传的Excel文件没有数据"));
            }

            // 读取表头，判断反查类型
            Row headerRow = sheet.getRow(0);
            String reverseType = determineReverseType(headerRow);
            
            if (reverseType == null) {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("无法识别Excel表头类型，请确保表头包含'Email'或'Phone'列"));
            }
            
            log.info("识别到反查类型: {}", reverseType);
            
            // 根据反查类型确定matchType (email->2, phone->1)
            Integer matchType;
            if ("email".equals(reverseType) || "Email".equals(reverseType) || "邮箱".equals(reverseType)){
                matchType = 2;
            } else if ("phone".equals(reverseType) || "Phone".equals(reverseType) || "手机号".equals(reverseType) || "电话号码".equals(reverseType)){
                matchType = 1;
            } else {
                return ResponseEntity.badRequest().body(Result.error("无法识别Excel表头类型，请确保表头包含'邮箱 / Email '或'手机号 / 电话号码 / Phone '列"));
            }


            // 获取表头列索引
            Map<String, Integer> headerMap = new HashMap<>();
            Integer valueColumnIndex = null; // 存储反查值的列索引
            
            for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerName = cell.getStringCellValue();
                    String headerLower = headerName.toLowerCase().trim();
                    headerMap.put(headerLower, i);
                    
                    // 找到反查值对应的列索引
                    if ("email".equals(reverseType) && (headerLower.contains("email") || headerLower.contains("邮箱"))) {
                        valueColumnIndex = i;
                    } else if ("phone".equals(reverseType) && (headerLower.contains("phone") || headerLower.contains("电话") || headerLower.contains("手机"))) {
                        valueColumnIndex = i;
                    }
                }
            }
            
            if (valueColumnIndex == null) {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("无法找到反查值列，请确保表头包含对应的Email/邮箱或Phone/电话列"));
            }

            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getReverseLookupRemaining() <= 0) {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("您的反查次数余额不足，请充值后再使用"));
            }

            // 准备结果文件
            Workbook resultWorkbook = new XSSFWorkbook();

            // 创建六个sheet对应不同数据源，根据matchType动态生成表头
            Sheet facebookSheet = createSheetWithHeader(resultWorkbook, "Facebook数据", getFacebookHeaders(matchType));
            Sheet twitterSheet = createSheetWithHeader(resultWorkbook, "Twitter数据", getTwitterHeaders(matchType));
            Sheet linkedinSheet = createSheetWithHeader(resultWorkbook, "LinkedIn数据", getLinkedInHeaders(matchType));
            Sheet companySheet = createSheetWithHeader(resultWorkbook, "全球企业库", getCompanyHeaders(matchType));
            Sheet buyerSheet = createSheetWithHeader(resultWorkbook, "广交会采购商", getBuyerHeaders(matchType));
            Sheet exhibitorSheet = createSheetWithHeader(resultWorkbook, "广交会展商", getExhibitorHeaders(matchType));

            // 统计各数据源找到的结果数量
            Map<String, Integer> resultCounts = new HashMap<>();
            resultCounts.put("facebook", 0);
            resultCounts.put("twitter", 0);
            resultCounts.put("linkedin", 0);
            resultCounts.put("company", 0);
            resultCounts.put("buyer", 0);
            resultCounts.put("exhibitor", 0);

            // 遍历数据行
            for (int rowNum = 1; rowNum < totalRows; rowNum++) {
                Row dataRow = sheet.getRow(rowNum);
                if (dataRow == null) continue;

                // 获取反查值（邮箱或电话）- 使用找到的列索引
                String searchValue = getCellStringValue(dataRow, valueColumnIndex);
                
                if (searchValue == null || searchValue.trim().isEmpty()) {
                    continue;
                }

                // 并行搜索六个数据源
                List<CompletableFuture<Void>> searchTasks = new ArrayList<>();

                // 搜索Facebook数据
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> results = emailReverseCheckService.searchFacebookByValue(searchValue, reverseType);
                        if (!results.isEmpty()) {
                            synchronized (facebookSheet) {
                                for (Map<String, Object> result : results) {
                                    Map<String, Object> mappedData = mapFacebookData(result, matchType);
                                    addDataToSheet(facebookSheet, mappedData, getFacebookHeaders(matchType));
                                    resultCounts.put("facebook", resultCounts.get("facebook") + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索Facebook数据异常: searchValue={}", searchValue, e);
                    }
                }, executorService));

                // 搜索Twitter数据（只在邮箱类型时查询）
                if ("email".equals(reverseType)) {
                    searchTasks.add(CompletableFuture.runAsync(() -> {
                        try {
                            List<Map<String, Object>> results = emailReverseCheckService.searchTwitterByEmail(searchValue);
                            if (!results.isEmpty()) {
                                synchronized (twitterSheet) {
                                    for (Map<String, Object> result : results) {
                                        Map<String, Object> mappedData = mapTwitterData(result, matchType);
                                        addDataToSheet(twitterSheet, mappedData, getTwitterHeaders(matchType));
                                        resultCounts.put("twitter", resultCounts.get("twitter") + 1);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.error("搜索Twitter数据异常: searchValue={}", searchValue, e);
                        }
                    }, executorService));
                }

                // 搜索LinkedIn数据
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> results = emailReverseCheckService.searchLinkedInByValue(searchValue, reverseType);
                        if (!results.isEmpty()) {
                            synchronized (linkedinSheet) {
                                for (Map<String, Object> result : results) {
                                    Map<String, Object> mappedData = mapLinkedInData(result, matchType);
                                    addDataToSheet(linkedinSheet, mappedData, getLinkedInHeaders(matchType));
                                    resultCounts.put("linkedin", resultCounts.get("linkedin") + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索LinkedIn数据异常: searchValue={}", searchValue, e);
                    }
                }, executorService));

                // 搜索全球企业库数据
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> results = emailReverseCheckService.searchCompanyByValue(searchValue, reverseType);
                        if (!results.isEmpty()) {
                            synchronized (companySheet) {
                                for (Map<String, Object> result : results) {
                                    Map<String, Object> mappedData = mapCompanyData(result, matchType);
                                    addDataToSheet(companySheet, mappedData, getCompanyHeaders(matchType));
                                    resultCounts.put("company", resultCounts.get("company") + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索全球企业库数据异常: searchValue={}", searchValue, e);
                    }
                }, executorService));

                // 搜索广交会采购商数据
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> results = emailReverseCheckService.searchBuyerByValue(searchValue, reverseType);
                        if (!results.isEmpty()) {
                            synchronized (buyerSheet) {
                                for (Map<String, Object> result : results) {
                                    Map<String, Object> mappedData = mapBuyerData(result, matchType);
                                    addDataToSheet(buyerSheet, mappedData, getBuyerHeaders(matchType));
                                    resultCounts.put("buyer", resultCounts.get("buyer") + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索广交会采购商数据异常: searchValue={}", searchValue, e);
                    }
                }, executorService));

                // 搜索广交会展商数据
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> results = emailReverseCheckService.searchExhibitorByValue(searchValue, reverseType);
                        if (!results.isEmpty()) {
                            synchronized (exhibitorSheet) {
                                for (Map<String, Object> result : results) {
                                    Map<String, Object> mappedData = mapExhibitorData(result, matchType);
                                    addDataToSheet(exhibitorSheet, mappedData, getExhibitorHeaders(matchType));
                                    resultCounts.put("exhibitor", resultCounts.get("exhibitor") + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索广交会展商数据异常: searchValue={}", searchValue, e);
                    }
                }, executorService));

                // 等待所有搜索任务完成
                CompletableFuture.allOf(searchTasks.toArray(new CompletableFuture[0])).join();
            }

            workbook.close();

            // 计算总扣除额度
            int totalDeduction = resultCounts.values().stream().mapToInt(Integer::intValue).sum();

            // 检查余额是否足够
            if (userBalance.getReverseLookupRemaining() < totalDeduction) {
                resultWorkbook.close();
                return ResponseEntity.badRequest().body(Result.error("您的反查次数余额不足，需要扣除 " + totalDeduction + " 次，当前余额 " + userBalance.getReverseLookupRemaining() + " 次"));
            }

            // 移除没有数据的sheet
            removeEmptySheets(resultWorkbook);

            // 扣除用户反查余额
            if (totalDeduction > 0) {
                userBalanceService.deductReverseLookup(userId, totalDeduction);
            }

            // 增加邮件反查次数统计
            workbenchStatsService.incrementEmailReverseCount(userId);

            // 将结果Excel写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            resultWorkbook.write(outputStream);
            resultWorkbook.close();

            byte[] excelBytes = outputStream.toByteArray();
            outputStream.close();

            // 设置响应头
            String resultFileName = "批量邮件反查结果_" + System.currentTimeMillis() + ".xlsx";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(resultFileName, "UTF-8"));
            headers.setContentLength(excelBytes.length);

            log.info("批量邮件反查完成: 处理{}行数据，扣除{}次额度", totalRows - 1, totalDeduction);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);

        } catch (Exception e) {
            log.error("批量邮件反查异常", e);
            return ResponseEntity.status(500).body(Result.error("批量邮件反查异常: " + e.getMessage()));
        }
    }

    // 判断反查类型（email或phone）
    private String determineReverseType(Row headerRow) {
        for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
            Cell cell = headerRow.getCell(i);
            if (cell != null) {
                String header = cell.getStringCellValue().toLowerCase().trim();
                if (header.contains("email") || header.contains("邮箱")) {
                    return "email";
                } else if (header.contains("phone") || header.contains("电话") || header.contains("手机")) {
                    return "phone";
                }
            }
        }
        return null;
    }

    // 创建带表头的sheet
    private Sheet createSheetWithHeader(Workbook workbook, String sheetName, String[] headers) {
        Sheet sheet = workbook.createSheet(sheetName);
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        return sheet;
    }

    // 移除没有数据的sheet
    private void removeEmptySheets(Workbook workbook) {
        for (int i = workbook.getNumberOfSheets() - 1; i >= 0; i--) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet.getLastRowNum() <= 0) {
                log.info("移除空sheet: {}", sheet.getSheetName());
                workbook.removeSheetAt(i);
            }
        }
    }

    // 添加数据到sheet
    private void addDataToSheet(Sheet sheet, Map<String, Object> data, String[] headers) {
        int lastRowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(lastRowNum + 1);

        for (int i = 0; i < headers.length; i++) {
            String header = headers[i];
            Object value = data.get(header);
            Cell cell = row.createCell(i);

            if (value != null) {
                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Number) {
                    cell.setCellValue(((Number) value).doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue((Date) value);
                } else {
                    cell.setCellValue(value.toString());
                }
            } else {
                cell.setCellValue("");
            }
        }
    }

    // 获取单元格字符串值
    private String getCellStringValue(Row row, Integer columnIndex) {
        if (columnIndex == null || row == null) {
            return null;
        }
        Cell cell = row.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue().trim();
            case NUMERIC -> String.valueOf((long) cell.getNumericCellValue());
            case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
            default -> null;
        };
    }

    // 各数据源的表头定义（复用IntelligentSearchController的逻辑）
    private String[] getFacebookHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            return new String[]{ "FacebookID", "姓名", "电话", "性别", "工作地点", "所在城市",  "出生地点", "个人状态", "出生日期", "加入时间"};
        } else {
            return new String[]{ "FacebookID", "姓名", "邮箱", "性别", "工作地点", "所在城市",  "出生地点", "个人状态", "出生日期", "加入时间"};
        }
    }

    private String[] getTwitterHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            return new String[]{ "姓名", "屏幕名", "粉丝数", "创建时间"};
        } else {
            return new String[]{ "姓名", "邮箱", "屏幕名", "粉丝数", "创建时间"};
        }
    }

    private String[] getLinkedInHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            return new String[]{"公司名", "人名", "网址",  "职位", "行业", "电话", "手机号", "位置",  "地点", "国家", "公司规模", "twitter用户", "twitter链接", "LinkedIn链接", "GitHub链接", "Facebook链接" };
        } else {
            return new String[]{"公司名", "人名", "网址",  "职位", "行业", "邮箱", "位置",  "地点", "国家", "公司规模", "twitter用户", "twitter链接", "LinkedIn链接", "GitHub链接", "Facebook链接" };
        }
    }

    private String[] getCompanyHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            return new String[]{"公司名", "姓名", "职位", "省份", "行业", "子行业", "员工规模", "收入规模", "电话", "手机号", "网址", "地址", "邮编"};
        } else {
            return new String[]{"公司名", "姓名", "职位", "省份", "行业", "子行业", "员工规模", "收入规模", "网址", "邮箱", "地址", "邮编"};
        }
    }

    private String[] getBuyerHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            return new String[]{"公司名", "联系人", "国家/地区", "采购类型", "网址", "电话", "传真", "地址", "邮编", "广交会届数"};
        } else {
            return new String[]{"公司名", "联系人", "国家/地区", "采购类型", "网址", "邮箱", "传真", "地址", "邮编", "广交会届数"};
        }
    }

    private String[] getExhibitorHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            return new String[]{"公司名", "公司类型", "公司简介",  "联系人", "手机号", "固定电话", "网址", "地址", "传真", "邮编", "行业", "省份", "展位号", "主要产品", "公司规模", "成立年份", "注册资金", "历史参展", "届次"};
        } else {
            return new String[]{"公司名", "公司类型", "公司简介",  "联系人", "网址", "地址",  "邮箱" , "传真", "邮编", "行业", "省份", "展位号", "主要产品", "公司规模", "成立年份", "注册资金", "历史参展", "届次"};
        }
    }

    // 数据映射方法（复用IntelligentSearchController的逻辑）
    private Map<String, Object> mapFacebookData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        mapped.put("FacebookID", source.get("facebook_id"));
        mapped.put("姓名", source.get("name"));
        
        if (matchType != null && matchType == 1) {
            mapped.put("电话", source.get("phone"));
        } else {
            mapped.put("邮箱", source.get("email"));
        }
        
        mapped.put("性别", source.get("gender"));
        mapped.put("工作地点", source.get("workplace"));
        mapped.put("所在城市", source.get("current_location"));
        mapped.put("出生地点", source.get("hometown"));
        mapped.put("个人状态", source.get("relationship_status"));
        mapped.put("出生日期", source.get("date"));
        mapped.put("加入时间", source.get("join_date"));
        return mapped;
    }

    private Map<String, Object> mapTwitterData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        mapped.put("姓名", source.get("name"));
        
        if (matchType != null && matchType == 2) {
            mapped.put("邮箱", source.get("email"));
        }
        
        mapped.put("屏幕名", source.get("screen_name"));
        mapped.put("粉丝数", source.get("followers"));
        mapped.put("创建时间", source.get("created_at"));
        return mapped;
    }

    private Map<String, Object> mapLinkedInData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        mapped.put("公司名", source.get("company_name"));
        mapped.put("人名", source.get("full_name"));
        mapped.put("网址", source.get("company_website"));
        mapped.put("职位", source.get("job_title"));
        mapped.put("行业", source.get("industry"));
        
        if (matchType != null && matchType == 1) {
            mapped.put("电话", source.get("phone_numbers"));
            mapped.put("手机号", source.get("phone_numbers"));
        } else {
            mapped.put("邮箱", source.get("emails"));
        }
        
        mapped.put("位置", source.get("location"));
        mapped.put("地点", source.get("location"));
        mapped.put("国家", source.get("country"));
        mapped.put("公司规模", source.get("company_size"));
        mapped.put("twitter用户", source.get("twitter_username"));
        mapped.put("twitter链接", source.get("twitter_url"));
        mapped.put("LinkedIn链接", source.get("linkedin_url"));
        mapped.put("GitHub链接", source.get("github_url"));
        mapped.put("Facebook链接", source.get("facebook_url"));
        return mapped;
    }

    private Map<String, Object> mapCompanyData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        
        String fullName = "";
        Object firstName = source.get("first_name");
        Object middleName = source.get("middle_name");
        Object lastName = source.get("last_name");
        
        if (firstName != null && !firstName.toString().isEmpty()) {
            fullName += firstName;
        }
        if (middleName != null && !middleName.toString().isEmpty()) {
            if (!fullName.isEmpty()) fullName += " ";
            fullName += middleName;
        }
        if (lastName != null && !lastName.toString().isEmpty()) {
            if (!fullName.isEmpty()) fullName += " ";
            fullName += lastName;
        }
        
        mapped.put("公司名", source.get("company_name"));
        mapped.put("姓名", fullName);
        mapped.put("职位", source.get("title"));
        mapped.put("省份", source.get("state"));
        mapped.put("行业", source.get("industry"));
        mapped.put("子行业", source.get("sub_industry"));
        mapped.put("员工规模", source.get("employee_size"));
        mapped.put("收入规模", source.get("revenue_size"));
        
        if (matchType != null && matchType == 1) {
            mapped.put("电话", source.get("phone"));
            mapped.put("手机号", source.get("mobile"));
        } else {
            mapped.put("邮箱", source.get("email"));
        }
        
        mapped.put("网址", source.get("web_address"));
        mapped.put("地址", source.get("address"));
        mapped.put("邮编", source.get("zip_code"));
        return mapped;
    }

    private Map<String, Object> mapBuyerData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        mapped.put("公司名", source.get("company_name"));
        mapped.put("联系人", source.get("contact_person"));
        mapped.put("国家/地区", source.get("country"));
        mapped.put("采购类型", source.get("purchase_type"));
        mapped.put("网址", source.get("website"));
        
        if (matchType != null && matchType == 1) {
            mapped.put("电话", source.get("phone"));
        } else {
            mapped.put("邮箱", source.get("email"));
        }
        
        mapped.put("传真", source.get("fax"));
        mapped.put("地址", source.get("address"));
        mapped.put("邮编", source.get("zip_code"));
        mapped.put("广交会届数", source.get("session_info"));
        return mapped;
    }

    private Map<String, Object> mapExhibitorData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        mapped.put("公司名", source.get("company_name"));
        mapped.put("公司类型", source.get("company_type"));
        mapped.put("公司简介", source.get("company_description"));
        mapped.put("联系人", source.get("contact_person"));
        
        if (matchType != null && matchType == 1) {
            mapped.put("手机号", source.get("mobile"));
            mapped.put("固定电话", source.get("phone"));
        } else {
            mapped.put("邮箱", source.get("email"));
        }
        
        mapped.put("网址", source.get("website"));
        mapped.put("地址", source.get("address"));
        mapped.put("传真", source.get("fax"));
        mapped.put("邮编", source.get("zip_code"));
        mapped.put("行业", source.get("category"));
        mapped.put("省份", source.get("province"));
        mapped.put("展位号", source.get("booth_number"));
        mapped.put("主要产品", source.get("main_products"));
        mapped.put("公司规模", source.get("company_size"));
        mapped.put("成立年份", source.get("established_year"));
        mapped.put("注册资金", source.get("registered_capital"));
        mapped.put("历史参展", source.get("exhibition_history"));
        mapped.put("届次", source.get("session_info"));
        return mapped;
    }

    /**
     * 下载批量反查模板
     * @param lang 语言（zh/en）
     * @param type 类型（email/phone）
     */
    @GetMapping("/batch/template")
    public ResponseEntity<byte[]> downloadTemplate(
            @RequestParam(defaultValue = "zh") String lang,
            @RequestParam(defaultValue = "email") String type) {
        try {
            String templatePath;
            String fileName;
            
            if ("en".equals(lang)) {
                if ("phone".equals(type)) {
                    templatePath = "static/templates/e-mail/E-mail Backcheck_Pone.xls";
                    fileName = "E-mail_Backcheck_Phone.xls";
                } else {
                    templatePath = "static/templates/e-mail/E-mail Backcheck_Email.xls";
                    fileName = "E-mail_Backcheck_Email.xls";
                }
            } else {
                if ("phone".equals(type)) {
                    templatePath = "static/templates/e-mail/邮件反查_Phone.xls";
                    fileName = "邮件反查_Phone.xls";
                } else {
                    templatePath = "static/templates/e-mail/邮件反查_Email.xls";
                    fileName = "邮件反查_Email.xls";
                }
            }
            
            Resource resource = new ClassPathResource(templatePath);
            InputStream inputStream = resource.getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            inputStream.close();
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(fileName, "UTF-8"));
            headers.setContentLength(bytes.length);
            
            return ResponseEntity.ok().headers(headers).body(bytes);
        } catch (Exception e) {
            log.error("下载模板失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }
} 